var express = require('express')
var router = express.Router()
let models = require('../models')
const Result = require('../utils/Result')

router.get('/', async (req, res) => {
    res.send('ok....')
})


/**
 *  @Router post /types/addEidtType
 *  @desc 新增编辑分类
 *  @access 接口是私有的
 */
router.post('/addEidtType', async (req, res) => {
    if(req.body.id){
        let result = await models.Type.update(req.body,{where:{id:req.body.id}})
        console.log(result)
        new Result(result,`修改 ${req.body.className} 分类成功`).success(res)
    }else{
        let result = await models.Type.create(req.body)
        new Result(result,`新增 ${result.className} 分类成功`).success(res)
    }
})

/**
 *  @Router get /types/getAllType
 *  @desc   获取所有分类
 *  @access 接口是公开的
 */
router.get('/all', async (req, res) => {
    let result = await models.Type.findAll({raw:true})
    const allNums = await models.Article.count()
    let task = []
    result.forEach( async t => task.push(models.Article.count({where:{typeId:t.id}})))
    let promiseData = await Promise.all(task)
    let sumArr = [{className:"全部",count:allNums,id:null,classDesc:"汇总分类【默认分类】",createdAt:new Date(),updatedAt:new Date()}]
    result.forEach( (t,i) => t.count = promiseData[i])
    result = [...sumArr, ...result]
    new Result(result,'获取所有分类成功').success(res)
})

/**
 *  @Router get /types/getTypeDetail/xxxx
 *  @desc   获取单个分类详情
 *  @access 接口是公开的
 */
router.get('/getTypeDetail/:id', async (req, res) => {
    var types = await models.Type.findOne({
        where:{id:req.params.id},
        include: [models.Article]
    }) //findByPk查找主键id
    res.json({data:types})
})

/**
 *  @Router post /types/detele
 *  @desc   删除单个分类详情
 *  @access 接口是私有的
 */
router.post('/delete', async (req, res) => {
	const { id } = req.body
	if(!id){
		return new Result(null,'此分类不可删除！').fail(res)
	}
	const article = await models.Article.count({where:{typeId:id}})
	if(article){
		return new Result(null,'该分类下还有文章，暂不能删除！').fail(res)
	}
	let result = await models.Type.destroy({
			where:{id:req.body.id}
	})
	new Result(null,'删除成功').success(res)
})


module.exports =  router